package com.dong.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.dong.domain.Message;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Value;

import java.io.IOException;
import java.net.URISyntaxException;
import java.util.Objects;

/**
 * @description: 消息处理器
 * @author: DongJian
 * @create: 2021-08-0113:33
 */
@Slf4j
public class MessageManager {
    @Value("${ocr.url}")
    private String ocrUrl;

    @Value("${ocr.connectTimeOut}")
    private Integer connectTimeOut;

    @Value("${ocr.readTimeOut}")
    private Integer readTimeOut;


    public static boolean sendMessage(Message message, String webHookAddress) throws URISyntaxException, IOException {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        JSONObject jsonObject = null;
        try {
            HttpPost httpPost = new HttpPost(webHookAddress);
            httpPost.setHeader("Content-Type","application/json; charset=utf-8");
            httpPost.setEntity(new StringEntity(JSON.toJSONString(message),"utf-8"));
            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity responseEntity = httpResponse.getEntity();
            if (Objects.nonNull(responseEntity)) {
                String result = EntityUtils.toString(responseEntity, "utf-8");
                log.info(">>>>消息发送返回结果>>>>{}", result);
                jsonObject = JSON.parseObject(result);
                String code = jsonObject.getString("errcode");
                if ("0".equals(code)) {
                    log.info("消息发送成功!");
                    return true;
                }
            }
            log.error("消息发送失败, 错误信息如下: {}", jsonObject.getString("errmsg"));
            return false;
        } catch (IOException e) {
            log.error("消息发送失败, 异常信息如下: {}", e.getMessage());
            return false;
        }
    }

    private RequestConfig getRequestConfig() {
        return RequestConfig.custom()
                .setConnectTimeout(connectTimeOut).setConnectionRequestTimeout(connectTimeOut)
                .setSocketTimeout(readTimeOut).build();
    }
}
